// pages/databaseGuide/databaseGuide.js
const app = getApp()

Page({
  data: {
    userInfoFlagYes: true,
    userInfoFlagNo: false,
  },

  onLoad: function (options) {
    this.setData({
      avatarUrl: app.globalData.avatarUrl,
      nickName: app.globalData.nickName,
    })
    this.onQuery();
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  onAdd: function (e) {
      var nickName = app.globalData.nickName;
    if (e.detail.value.name != null && e.detail.value.name != '' && e.detail.value.name != undefined ){
         nickName =  e.detail.value.name
       }

    const db = wx.cloud.database()
    console.info("e.detail.value.wechatNo:" + e.detail.value.wechatNo);
    console.info(" e.detail.value.phone:" + e.detail.value.phone);
    console.info("e.detail.value.date:" + e.detail.value.date);
    db.collection('PUSER').add({
       data: {
         nickName: nickName,
         wechatNo: e.detail.value.wechatNo,
         company: e.detail.value.company,
         hoursezone: e.detail.value.hoursezone,
         phone: e.detail.value.phone,
         date: e.detail.value.date
       },
       success: res => {
         // 在返回结果中会包含新创建的记录的 _id
         wx.showToast({
           icon: 'none',
           title: '保存成功'
         })
         //wx.showToast({
          // title: '新增记录成功',
         //})
         console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
       },
       fail: err => {
         wx.showToast({
           icon: 'none',
           title: '新增记录失败'
         })
         console.error('[数据库] [新增记录] 失败：', err)
       }
     })
  },

  onQuery: function() {
     const db = wx.cloud.database()
     // 查询当前用户所有的 counters
    console.log('openid=' + app.globalData.openid);
     db.collection('PUSER').where({
       _openid: app.globalData.openid
     }).get({
       success: res => {
        this.setData({
          puser: res.data[res.data.length - 1],
          date: res.data[res.data.length - 1].date
         })
         console.log('[数据库] [查询记录] 成功: ', res);
       },
       fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
     })
  },

  goHome: function() {
    const pages = getCurrentPages()
    if (pages.length === 2) {
      wx.navigateBack()
    } else if (pages.length === 1) {
      wx.redirectTo({
        url: '../index/index',
      })
    } else {
      wx.reLaunch({
        url: '../index/index',
      })
    }
  }
})